package com.onejson.ojmall.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.onejson.ojmall.entity.ProductEntity;
import com.onejson.ojmall.entity.dto.ProductDTO;
import com.onejson.ojmall.entity.vo.ProductVO;
import com.onejson.ojmall.mapper.ProductMapper;
import com.onejson.ojmall.service.IProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductEntity> implements IProductService {

    @Resource
    private ProductMapper productMapper;

    @Override
    public List<ProductVO> getProductList(ProductEntity product) {
        List<ProductEntity> list = productMapper.selectProductList(product);
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public ProductVO getProductById(Long id) {
        ProductEntity product = this.getById(id);
        return convertToVO(product);
    }

    @Override
    public boolean addProduct(ProductDTO productDTO) {
        ProductEntity product = new ProductEntity();
        BeanUtils.copyProperties(productDTO, product);
        return this.save(product);
    }

    @Override
    public boolean updateProduct(ProductDTO productDTO) {
        ProductEntity product = new ProductEntity();
        BeanUtils.copyProperties(productDTO, product);
        return this.updateById(product);
    }

    @Override
    public boolean deleteProducts(Long[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }

    @Override
    public boolean onlineProduct(Long id) {
        ProductEntity product = new ProductEntity();
        product.setId(id);
        product.setStatus(1);
        return this.updateById(product);
    }

    @Override
    public boolean offlineProduct(Long id) {
        ProductEntity product = new ProductEntity();
        product.setId(id);
        product.setStatus(0);
        return this.updateById(product);
    }

    private ProductVO convertToVO(ProductEntity product) {
        if (product == null) {
            return null;
        }
        ProductVO vo = new ProductVO();
        BeanUtils.copyProperties(product, vo);
        return vo;
    }
} 